package com.codecrane.core.util;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.Random;

/**
 * 权重随机抽象工具类
 * Created by crane on 16/7/8.
 */
public abstract class WeightRandom<T> {
    public static <T> WeightRandom<T> build(Map<T, Integer> map, Class<? extends WeightRandom> implClazz) {
        if (!WeightRandom.class.isAssignableFrom(implClazz)) {
            throw new IllegalArgumentException("implClass");
        }
        try {
            Constructor<? extends WeightRandom> constructor = implClazz.getConstructor(Map.class);
            WeightRandom weightRandom = constructor.newInstance(map);
            weightRandom.init();
            return weightRandom;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected final Map<T, Integer> data;
    protected volatile Random ran;

    public WeightRandom(Map<T, Integer> data) {
        this.data = data;
        this.ran = new Random();
    }

    public abstract void init();

    public abstract T random();

    public abstract T random(int ran);

    public void reset() {
        this.ran = new Random();
    }
}
